package simple.form.utils;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import org.apache.log4j.Logger;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

/**
 * 二维码工具
 * Created by Administrator on 2017/2/22.
 */
public class QrcodeUtil {
    public static Logger log4j = Logger.getLogger(QrcodeUtil.class);
    /**
     * 默认宽高
     */
    public static int WIDTH = 300;
    public static int HEIGHT = 300;

    /**
     * 生成二维码
     * @param content  二维码内容
     * @return 图片
     */
    public static BufferedImage create(String content){
        return create(content,WIDTH,HEIGHT);
    }
    /**
     * 生成二维码
     * @param content  二维码内容
     * @param width 宽
     * @param height 高
     * @return 图片
     */
    public static BufferedImage create(String content,int width,int height){
        HashMap<EncodeHintType, String> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        BitMatrix matrix = null;
        try {
            matrix = new MultiFormatWriter().encode(content,
                    BarcodeFormat.QR_CODE, width, height, hints);

        } catch (WriterException e) {
            log4j.error("MultiFormatWriter encode error",e);
            return null;

        }
        BufferedImage  image = null;
        image =  MatrixToImageWriter.toBufferedImage(matrix);
        return image;
    }

    /***
     * 默认生成二维码(保存)
     * @param content  二维码内容
     * @param path     保存路径
     * @return
     */
    public static boolean create(String content,String path){
        return create(content,path,WIDTH,HEIGHT);
    }

    /***
     * 生成二维码(保存)
     * @param content  二维码内容
     * @param path     保存路径
     * @return
     */
    public static boolean create(String content,String path,int width,int height){
        if(content==null||content.isEmpty()){
            return  false;
        }
        if(path==null||path.isEmpty()){
            return  false;
        }
        if(width<=0||height<=0){
            return  false;
        }
        HashMap<EncodeHintType, String> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        BitMatrix matrix = null;
        try {
            matrix = new MultiFormatWriter().encode(content,
                    BarcodeFormat.QR_CODE, width, height, hints);

        } catch (WriterException e) {
            log4j.error("MultiFormatWriter  encode error",e);
            return false;

        }
        String imageSuffix = path.substring(path.indexOf(".")+1);
        File file = new File(path);
        try {
            MatrixToImageWriter.writeToPath(matrix,imageSuffix,file.toPath());
        } catch (IOException e) {
            log4j.error("MatrixToImageWriter writeToPath error",e);
            return false;

        }
        return true;
    }

    /**
     * 解析二维码
     * @param path
     * @return
     */
    public static String parse(String path){
        if(path==null||path.isEmpty()){
            return "";
        }
        String imageSuffix = path.substring(path.indexOf(".")+1);
        File file = new File(path);
        InputStream input = null;
        byte[] byteList = null;
        try {
            input = new FileInputStream(file);
            byteList = new byte[input.available()];
            input.read(byteList);
        } catch (IOException e) {
            log4j.error("parse file to byte[] error",e);
            return "";

        }
        return parse(byteList,imageSuffix);
    }

    /**
     * 解析二维码
     * @param byteList
     * @param imageSuffix 后缀名称
     * @return
     */
    public static String parse(byte[] byteList,String imageSuffix){
        BufferedImage bufferedImage = null;
        try {
            if("gif".equals(imageSuffix)||"GIF".equals(imageSuffix)){
                bufferedImage = GifDecoder.read(byteList).getFrame(0);
            }else{
                bufferedImage = ImageIO.read(new ByteArrayInputStream(byteList));
            }

        } catch (IOException e) {
            log4j.error("parse to BufferedImage error",e);
            return "";

        }
        LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        HashMap<DecodeHintType, String> hints = new HashMap<DecodeHintType, String>();
        hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
        Result result = null;
        try {
            result = new MultiFormatReader().decode(bitmap, hints);
        } catch (NotFoundException e) {
            log4j.error("parse to Result error",e);
            return "";
        }
        return  result!=null?result.getText():"";
    }


    public static void main(String[] args) {
        QrcodeUtil.create("test","D://qrcodeImage.jpg");
        System.out.printf(QrcodeUtil.parse("D://qrcodeImage.jpg"));
//        String path ="D://qrcodeImage.jpg";
//        String imageSuffix = path.substring(path.indexOf(".")+1);
//        System.out.println(imageSuffix);
    }
}
